<template>
  <a-form>
    <template v-if="type === this.CONFIG_TYPES.FILE">
      <a-form-item label="最大上传数">
        <a-input-number v-model="value.max" :min="1" :max="99"/>
      </a-form-item>
      <a-form-item label="文件类型">
        <a-input v-model="value.ext" placeholder="多个之间用英文逗号隔开"/>
      </a-form-item>
    </template>
    <template v-else-if="type === this.CONFIG_TYPES.DATE ||
      type === this.CONFIG_TYPES.DATETIME"
    >
      <a-form-item label="存储格式">
        <a-radio-group v-model="value.format">
          <a-radio value="datetime">日期时间</a-radio>
          <a-radio value="unixtime">Unix时间戳</a-radio>
        </a-radio-group>
      </a-form-item>
    </template>
    <template v-else-if="type === this.CONFIG_TYPES.SINGLE ||
      type === this.CONFIG_TYPES.MULTIPLE"
    >
      <a-form-item v-if="type === this.CONFIG_TYPES.MULTIPLE" label="存储格式">
        <a-radio-group v-model="value.format">
          <a-radio value="json">json格式</a-radio>
          <a-radio value="comma">逗号分隔</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="选项来源">
        <a-radio-group v-model="value.sample" @change="onSampleChange">
          <a-radio value="1">手动输入</a-radio>
          <a-radio value="2">从数据库导入</a-radio>
          <a-radio value="3">从配置项导入</a-radio>
        </a-radio-group>
      </a-form-item>
      <template v-if="value.sample==1" >
        <a-form-item label="选项设置" required>
          <a-input
            type="textarea"
            rows="13"
            v-model="value.options"
            :placeholder="'格式：\n'+placeholder[type][value.type]"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==2">
        <a-form-item label="选项设置" required>
          <code-mirror 
            ref="codemirror" 
            v-model="value.options"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==3">
        <a-form-item label="选项设置" required>
          <a-select v-model="value.options">
            <a-select-option 
              v-for="option in options" 
              :key="option.id" 
              :value="option.id"
            >
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </template>
      <a-form-item label="选择形式">
        <a-radio-group v-if="type === this.CONFIG_TYPES.SINGLE" v-model="value.type">
          <a-radio value="single_box" label="single_box">单选框</a-radio>
          <a-radio value="single_select" label="single_select">单选下拉</a-radio>
        </a-radio-group>
     
        <a-radio-group v-else-if="type === this.CONFIG_TYPES.MULTIPLE" v-model="value.type">
          <a-radio value="multiple_box" label="multiple_box">多选框</a-radio>
          <a-radio value="multiple_select" label="multiple_select">多选下拉</a-radio>
          <a-radio value="transfer" label="transfer">穿梭框</a-radio>
        </a-radio-group>
        <template v-else>
          无
        </template>
      </a-form-item>
    </template>

    <template v-else-if="type === this.CONFIG_TYPES.SELECT_TREE">
      <a-form-item label="选项来源">
        <a-radio-group v-model="value.sample"  @change="onSampleChange">
          <a-radio value="1">手动输入</a-radio>
          <a-radio value="2">从数据库导入</a-radio>
          <a-radio value="4">Json文件导入</a-radio>
        </a-radio-group>
      </a-form-item>
      <template v-if="value.sample==1" >
        <a-form-item label="选项设置" required>
          <a-input
            type="textarea"
            rows="13"
            v-model="value.options"
            :placeholder="'格式：\n'+placeholder[type][value.type]"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==2">
        <a-form-item label="选项设置" required>
          <code-mirror 
            ref="codemirror" 
            v-model="value.options"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==4">
        <a-form-item label="选项设置" required>
          <file-picker
            v-model="value.options"
            ext="json"
            valueFields="id,origin_filename,path"
          />
        </a-form-item>
      </template>
      <a-form-item label="选择形式">
        无
      </a-form-item>
    </template>

    <template v-else-if="type === this.CONFIG_TYPES.CASCADER">
      <a-form-item label="存储格式">
        <a-radio-group v-model="value.format">
          <a-radio value="json">json格式</a-radio>
          <a-radio value="comma">逗号分隔</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="选项来源">
        <a-radio-group v-model="value.sample"  @change="onSampleChange">
          <a-radio value="1">手动输入</a-radio>
          <a-radio value="2">从数据库导入</a-radio>
          <a-radio value="4">Json文件导入</a-radio>
        </a-radio-group>
      </a-form-item>
      <template v-if="value.sample==1" >
        <a-form-item label="选项设置" required>
          <a-input
            type="textarea"
            rows="13"
            v-model="value.options"
            :placeholder="'格式：\n'+placeholder[type][value.type]"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==2">
        <a-form-item label="选项设置" required>
          <code-mirror 
            ref="codemirror" 
            v-model="value.options"
          />
        </a-form-item>
      </template>
      <template v-if="value.sample==4">
        <a-form-item label="选项设置" required>
          <file-picker
            v-model="value.options"
            ext="json"
            valueFields="id,origin_filename,path"
          />
        </a-form-item>
      </template>
      <a-form-item label="选择形式">
        无
      </a-form-item>
    </template>
    <template v-else>
      <a-form-item class="ma-0">无</a-form-item>
    </template>
  </a-form>
</template>

<script>
import {
  getSystemModels,
} from '@/api/system-models'
import {
  getSelectConfigs,
} from '@/api/configs'
import { mapConstants } from '@/libs/constants'
import TypeInput from './TypeInput'
import _pick from 'lodash/pick'
import CodeMirror from '@c/CodeMirror'
import FilePicker from '@c/LzForm/FilePicker'

export default {
  name: 'TypeOptions',
  components: {
    TypeInput,
    CodeMirror,
    FilePicker,
  },
  data() {
    return {
      historySampleList: [], // Variable to store the previous value of options
      currentSample: {}, // Variable to store the previous value of options
      system_models: [],
      options: [],
      placeholder: {
        'single': {
          'single_box': '值1=>文字1\n值2=>文字2',
          'single_select': '值1=>文字1\n值2=>文字2',
        },
        'multiple': {
          'multiple_box': '值1=>文字1\n值2=>文字2',
          'multiple_select': '值1=>文字1\n值2=>文字2',
          'transfer': '值1=>文字1\n值2=>文字2',
        },
        'cascader': {
          'select': JSON.stringify([
            {
              value: "xxx",
              label: "xxx",
              children: [
                {
                  value: "xxx",
                  label: "xxx",
                }
              ]
            }
          ], null, 2),
        },
        'select_tree': {
          'select': JSON.stringify([
            {
              value: "xxx",
              label: "xxx",
              children: [
                {
                  value: "xxx",
                  label: "xxx",
                }
              ]
            }
          ], null, 2),
        }
      },
    }
  },
  model: {
    prop: 'value',
    event: 'change.value',
  },
  props: {
    type: String,
    value: Object,
  },
  computed: {
    ...mapConstants(['CONFIG_TYPES']),
  },
  created() {
    /**
     * 存储类型对应的 options
     * 用来在切换类型后，恢复原来设置的值
     */
    this.optionsBak = {}

    this.$on('field-reset', this.onReset)

    this.getSystemModels()

    this.getSelectConfigs()
  },
  beforeDestroy() {
    this.$off('field-reset', this.onReset)
  },
  methods: {
    onSampleChange() {
      // Store the previous value of options
      this.currentSample = this.value.options;
      
      // Clear the current value of options
      this.value.options = '';
    },
    onReset() {
      this.optionsBak = {}
      this.initOptions()
    },
    initOptions() {
      const type = this.type
      if (!type) {
        return
      }

      let defaultValue
      switch (type) {
        case this.CONFIG_TYPES.FILE:
          defaultValue = {
            max: 1,
            ext: '',
          }
          break
        case this.CONFIG_TYPES.DATE:
        case this.CONFIG_TYPES.DATETIME:
          defaultValue = {
            format: 'datetime',
          }
          break
        case this.CONFIG_TYPES.SINGLE:
        case this.CONFIG_TYPES.MULTIPLE:
          defaultValue = {
            options: '',
            type: 'input',
            sample: 1,
            format: 'json',
          }
          break
        case this.CONFIG_TYPES.CASCADER:
          defaultValue = {
            options: '',
            type: 'select',
            sample: 1,
            format: 'json',
          }
          break
        case this.CONFIG_TYPES.SELECT_TREE:
          defaultValue = {
            options: '',
            type: 'select',
            sample: 1,
          }
          break
        default:
          defaultValue = null
      }

      const v = defaultValue
        ? _pick(Object.assign({}, this.optionsBak[type] || defaultValue, this.value), Object.keys(defaultValue))
        : null
      // 存储类型对应的 options，用来还原
      this.optionsBak[type] = v
      this.$emit('change.value', v)
    },
    async getSystemModels() {
      const { data } = await getSystemModels({pluck:'slug',parent_id:0})
      this.system_models = data
    },
    async getSelectConfigs() {
      const { data } = await getSelectConfigs()
      this.options = data
    },
    onRefresh() {
      this.$router.replace({
        path: this.$route.fullPath,
        query: {
          _refresh: Date.now(),
        },
      })
    },
  },
  watch: {
    // 'value.sample'(newVal, oldVal) {
    //   if (oldVal) {
    //     this.historySampleList['sample'+oldVal] = this.currentSample
    //   }
    //   // When switching back, restore the previous value of options
    //   if (newVal) {
    //     this.value.options = this.historySampleList['sample'+newVal] ?? this.value.options;
    //   }
    // },
    type: {
      handler() {
        this.initOptions()
      },
      immediate: true,
    },
    $route() {
      // 路由变化会复用组件，清空一下
      this.optionsBak = {}
      this.onRefresh()
    },
    
  },
}
</script>

<style scoped lang="less">
.ant-form-item {
  margin-bottom: 0;
}
</style>
